package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private EmpMapper empMapper;

    /**
     * 分页查询
     *
     * @param param 分页查询参数update_time
     * @return 分页查询结果
     */
    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
        //创建分页对象
        Page<Emp> page = new Page<>(param.getPage(), param.getPageSize());

        page.addOrder(OrderItem.desc("update_time"));
/*        //调用page方法完成分页查询
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null,Emp::getEntryDate,param.getBegin(),param.getEnd());

        page = page(page);*/

        //利用lambdaQuery实现分页查询
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);
        //获取员工列表
        List<Emp> emps = page.getRecords();

        //获取员工所对应的部门id集合
        List<Long> deptIds = emps.stream().map(Emp::getDeptId).collect(Collectors.toList());
        //根据deptIds查询出所有员工所对应的的部门
        if (!deptIds.isEmpty()) {
            List<Dept> depts = deptService.listByIds(deptIds);

            //遍历集合拿到员工部门id所对应的部门名称给到员工
            emps.forEach(emp->{
                depts.forEach(dept->{
                    if(emp.getDeptId() != null && emp.getDeptId().equals(dept.getId())){
                        emp.setDeptName(dept.getName());
                    }
                });
            });
        }
        //返回分页查询结果
        return new PageResult<>(page.getTotal(), emps);
    }

    /**
     * 新增员工
     *
     * @param emp 员工参数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmp(Emp emp) {

        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        //保存员工
        save(emp);

        //获取员工经历
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && !exprList.isEmpty()) {
            //为每段工作经历添加员工id
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        }

        //调用EmpExprService添加员工工作经历
        empExprService.saveBatch(exprList);
    }

    /**
     * 根据id批量删除员工
     *
     * @param ids 员工id集合
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeEmpByIds(List<Integer> ids) {

        removeBatchByIds(ids);
        //创建条件对象
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EmpExpr::getEmpId, ids);
        //根据员工id删除员工工作经历
        empExprService.remove(queryWrapper);
    }

    /**
     * 根据id查员工
     *
     * @param id 员工id
     * @return 返回单个员工
     */
    @Override
    public Emp getEmpById(Integer id) {
        //创建员工对象
        Emp emp = getById(id);

        //创建条件对象
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmpExpr::getEmpId, id);
        List<EmpExpr> exprList = empExprService.list(queryWrapper);

        if (exprList != null && !exprList.isEmpty()) {
            emp.setExprList(exprList);
        }
        //将员工经历封装到员工对象中

        return emp;
    }

    /**
     * 修改员工
     *
     * @param emp 员工参数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateEmp(Emp emp) {
        // 调用service层方法修改员工信息
        // 根据id更新员工的基本信息
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
        // 根据id批量删除员工的工作经历信息
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmpExpr::getEmpId, emp.getId());
        empExprService.remove(queryWrapper);

        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && !exprList.isEmpty()) {
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        }
        empExprService.saveBatch(exprList);

    }

    /**
     * 统计员工各职位人数
     *
     * @return 职位统计对象
     */
    @Override
    public JobInfo getJobInfo() {
        JobInfo jobInfo = new JobInfo();
        //调用Mapper查询出职位名称和只为中的人数
        List<Map<String, Object>> jobInfos = empMapper.getJobInfo();

        List<Object> jobNames = jobInfos.stream().map(jobName -> jobName.get("jobName")).toList();
        List<Object> jobCount = jobInfos.stream().map(jobName -> jobName.get("jobCount")).toList();

        jobInfo.setJobList(jobNames);
        jobInfo.setDataList(jobCount);
        return jobInfo;
    }

    /**
     * 统计员工性别
     *
     * @return 统计性别的集合
     */
    @Override
    public List<Map<String, Object>> getGenderInfo() {
        List<Map<String,Object>> genderInfo = empMapper.getGenderInfo();
        return genderInfo;
    }
}
